<template>
  <el-form :model="userModel" :rules="rules" ref="userModel" label-width="100px" class="demo-ruleForm">
    <el-form-item style="margin-left: 20px">
      <h2>修改密码</h2>
    </el-form-item>
    <el-form-item label="旧密码" prop="password" style="width: 380px">
      <el-input v-model="userModel.password" type="password"></el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="newpassword" style="width: 380px">
      <el-input v-model="userModel.newpassword" type="password"></el-input>
    </el-form-item>
    <el-form-item label="确认密码" prop="repassword" style="width: 380px">
      <el-input v-model="userModel.repassword" type="password"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="danger" @click="submitForm('userModel')">确认修改</el-button>
      <el-button type="danger" plain @click="clearForm('userModel')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  export default {
    name: "UserCenter",
    data() {
      const repassAuth = (rule, value, callback) => {
        if (value !== this.userModel.newpassword)
          callback(new Error('两次密码输入不一致'))
        else
          callback()
      };
      return {
        userModel: {
          newpassword: '',
          password: '',
          repassword: ''
        },
        rules: {
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, message: '旧密码最小需要 6 位', trigger: 'blur'}
          ],
          newpassword: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, message: '新密码最小需要 6 位', trigger: 'blur'}
          ],
          repassword: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {validator: repassAuth, trigger: 'blur'}
          ]
        },
      }
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {

            this.$http.post('/sys/user/updatePass', this.userModel).then(res => {
              if(res.data.code === 200) {
                this.$message({
                  showClose: true,
                  message: '更新密码成功',
                  type: 'success',
                  onClose: () => {
                    this.getUserList()
                  }
                })
              } else {
                this.$message.error(this.data.msg)
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      clearForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }
</script>

<style scoped>

</style>
